<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\mill\admin;

use app\mill\builder\Admin;
use app\mill\builder\ZBuilder;
use app\mill\model\Client as ClientModel;
use app\mill\model\Order as OrderModel;
use app\mill\model\Stat as StatModel;
use app\mill\model\Archives as ArchivesModel;
use app\mill\model\Give as GiveModel;
use think\Db;
use think\facade\Env;

/**
 * 客户控制器
 * @package app\admin\controller
 */
class Client extends Admin
{
    //初始化
    protected function initialize(){
        parent::initialize();
        GiveModel::init();
    }
    //首页
    public function index(){

        $option = "{
                        legend: {
                            data: ['新增客户']
                        },
                        tooltip: {
                            trigger: 'axis',//鼠标浮动效果
                        },
                        xAxis: {
                            type: 'category',
                            data: data.head
                        },
                        grid: {
                            left: 15,
                            right: 15,
                            bottom: 0,
                            top:30,
                            containLabel: true
                        },
                        yAxis: {
                            type: 'value',
                            axisLine: {
                                show: false  // 取消纵坐标的标线
                            },
                            axisTick: {
                                show: false  // 取消纵坐标的刻度线
                            },
                            splitLine: {
                                show: false
                            }
                        },
                        series: [
                            {
                                name: '新增客户',
                                data: data.data,
                                type: 'line',
                                barWidth:48,
                                smooth:true,
                                areaStyle: {},
                                itemStyle:{
                                    color:'#568AEC'
                                }
                            }
                        ]
                    }";
        $url = url('mill/stat/ajaxClient');
        $top_html = StatModel::topStatHtml($url,$option,['charts','rank','year']);

        //获取菜单列表
        $menu = StatModel::getMenu('mill',268);
        //额外HTML代码
        $extra_html = StatModel::fixedHtml($menu);

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('') // 页面标题
            ->setTableName('mill_client') // 设置表名
            ->setExtraHtml($top_html,'block_top')
            ->setExtraHtml($extra_html)
            ->fetch(); // 渲染模板
    }
    //客户列表
    public function lists()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $sales_id = input('sales_id');
        // 获取查询条件
        $map = $this->getMap();
        if(!empty($sales_id))$map[] = ['c.sales_id','=',$sales_id];
        // 数据列表
        $data_list = Db::name('mill_client')
            ->alias('c')
            ->field('c.*,ss.staff as back,s.staff as sales,s.staff_mobile as sales_mobile')
            ->leftJoin('mill_order o','o.client_id=c.id')
            ->leftJoin('mill_staff s','c.sales_id=s.id')
            ->leftJoin('mill_staff ss','c.back_id=ss.id')
            ->where($map)
            ->group('c.id')
            ->order('c.id desc')
            ->paginate()
            ->each(function ($v){

                $v['create_time'] = date('Y-m-d',$v['create_time']);
                $v['company'] = $v['company'].ClientModel::getTags($v);
                $v['sales_mobile'] = '<font color="#68FF84">'.$v['sales_mobile'].'</font>';
                $v['note'] = '<font color="#DA0000">'.$v['note'].'</font>';

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('客户列表('.$data_list->total().')') // 页面标题
            ->setTableName('mill_client') // 设置表名
            //->hideCheckbox()
            ->setSearch(['c.company' => '客户名称', 'c.nickname' => '联系人', 'c.mobile' => '电话']) // 设置搜索参数
            ->setSearchArea([
                ['daterange:2', 'c.create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['company', '客户名称','jump_bottom','','client_id=__id__','must-green',['group'=>'客户信息']],
                ['nickname', '客户联系人','','','','must',['group'=>'客户信息']],
                ['mobile', '联系方式','','','','must',['group'=>'客户信息']],
                ['address', '联系地址','','','','must',['group'=>'客户信息']],
                ['sales', '业务经理','','','','',['group'=>'客户信息']],
                ['sales_mobile', '业务电话','','','','',['group'=>'客户信息']],
                ['back', '内勤','','','','badge-warning',['group'=>'客户信息']],
                ['note', '备注','','','','badge-warning',['group'=>'其他信息']],
                ['is_lock','冻结','switch2','','','badge-warning',['group'=>'其他信息']],
            ])
            ->addTopButton('print',['title' => '导出列表','icon'=>'','class'=>'btn btn-success quality-print','float'=>'right','lay-event'=>'quality-print'])
            ->addTopButton('add',['title' => '新增客户','href'=>url('mill/client/add'),'class'=>'btn btn-default','float'=>'left'])
            ->addTopButton('edit',['title' => '修改客户','href'=>url('mill/client/add'),'class'=>'btn btn-default js-get'])
            ->addTopButton('delete',['title' => '删除客户'],false)
            ->addTopButton('isLock',['title' => '客户冻结','href'=>url('mill/client/isLock'),'class'=>'btn btn-danger  ajax-post confirm'],false)
            ->addTopButton('backs',['title' => '客户归属','href'=>url('mill/client/back'),'class'=>'btn btn-default','float'=>'left'])
            ->addTopButton('change',['title' => '客户继承','href'=>url('mill/client/change'),'class'=>'btn btn-default'])
            ->addTopButton('add',['title' => '新增客户工程','href'=>url('mill/order/add'),'class'=>'btn btn-default dch-js-get','target-form'=>'client_id'])
            ->addRightButtons('edit') // 批量添加右侧按钮
            ->addRightButton('order', ['title' => '添加工程', 'href' => url('mill/order/add', [ 'client_id' => '__id__']), 'icon' => ''])
            ->addRightButton('order', ['title' => '查看工程', 'href' => url('mill/order/index')."?_s=client_id=__id__&_o=client_id=eq", 'icon' => ''])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 130,
                'mobile'  => 130,
                'sales'  => 130,
                'back'  => 130,
                'nickname'  => 130,
                'sales_mobile'  => 130,
                'address'  => 150,
                'is_lock'  => 130,
            ])
            ->fetch(); // 渲染模板
    }
    //新增
    public function add()
    {
        $id = input('ids');
        if (strpos($id, ',') !== false)$this->error('暂不支持批量修改');
        $info = [];
        $sales_list = ClientModel::getStaffList(1);
        $back_list = ClientModel::getStaffList(2);

        if ($this->request->isPost()) {
            $data = input();
            // 验证
            $result = $this->validate($data, 'Client');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);

            if(empty($id))$data['create_time'] = time();
            $data['update_time'] = time();
            $data['back'] = isset($back_list[$data['back_id']])?$back_list[$data['back_id']]:'';

            if($id)$re = Db::name('mill_client')->where(['id'=>$id])->update($data);
            else $re = Db::name('mill_client')->insertGetId($data);

            //关闭子窗口，并刷新父窗口
            if ($re)$this->success('操作成功','','_parent_reload');
            $this->error('操作失败');
        }

        if($id)$info = Db::name('mill_client')->where(['id'=>$id])->find();

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    // 业务电话
                    var sales_list = '.json_encode(ClientModel::getStaffList(1,'*')).';
                    // 业务内勤
                    $("body").on("change","select[name=\'sales_id\']",function(){
                        var sales_id = $(this).find("option:selected").val();
                        var sales_mobile = sales_list[sales_id] ? sales_list[sales_id][\'staff_mobile\'] : "";
                        var sales = sales_list[sales_id] ? sales_list[sales_id][\'staff\'] : "";
                        
                        $("input[name=\'sales\']").val(sales);
                        $("input[name=\'sales_mobile\']").val(sales_mobile);
                    });
                })
            </script>';

        return ZBuilder::make('form')
            ->setPageTitle('新增客户') // 页面标题
            ->addFormItems([ // 批量添加表单项
                ['ititle', 'ititle1', '客户项'],
                ['ititle', 'ititle2', '公司项'],
                ['text:||||must', 'company', '客户名称'],
                ['select', 'back_id', '内勤人员','',$back_list],
                ['text', 'nickname', '客户联系人'],
                ['select', 'sales_id', '业务内勤','',$sales_list],
                ['text', 'mobile', '客户电话'],
                ['text', 'sales_mobile', '业务电话'],
                ['text', 'address', '客户地址'],
                ['select', 'point', '重要程度','',ClientModel::$point],
                ['textarea:12', 'note', '备注'],
                ['hidden', 'sales', '业务内勤'],
                ['ititle:12', 'ititle3', '选择项'],
                ['radio:4', 'type', '客户类型','',ClientModel::$types,0],
                ['radio:8', 'mill_id', '公司选择','',ClientModel::getMillList(),1],
            ])
            ->setFormData($info)
            ->setExtraJs($js)
            //->layout(['note'=>12])
            ->fetch();
    }
    //业务经理列表
    public function saleList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();

        //产品最后一个的状态
        $last_give_status = GiveModel::$last_give_status;

        // 数据列表
        $data_list = Db::name('mill_staff')
            ->alias('s')
            ->field("s.*,{$last_give_status} as last_give_status,count(DISTINCT c.id) as client_count,GROUP_CONCAT(DISTINCT o.id) as order_ids,sum(o.archives_number_sum) as number_sum,sum(o.archives_area_sum) as area_sum,sum(o.address_number) as address_number,sum(o.address_area) as address_area")
            ->leftJoin('mill_client c','c.sales_id=s.id')
            ->leftJoin('mill_order o','o.sales_id=s.id')
            ->where($map)
            ->where(['s.type'=>1])
            ->group('s.id')
            ->order('s.id desc')
            ->paginate();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('业务经理') // 页面标题
            ->setTableName('mill_staff') // 设置表名
            //->hideCheckbox()
            ->setSearch(['c.company' => '客户公司', 'o.engineering' => '工程名称', 's.staff' => '业务经理']) // 设置搜索参数
            ->addColumns([ // 批量添加列
                ['staff', '业务经理','jump_right','','sales_id=__id__','badge-green',['group'=>'业务详情']],
                ['client_count', '客户数','','','','',['group'=>'业务详情']],
                ['area_sum', '总面积(m²)','','','','',['group'=>'业务详情']],
                ['address_area', '完成面积(m²)','','','','',['group'=>'业务详情']],
            ])
            ->addTopButton('print',['title' => '导出列表','icon'=>'','class'=>'btn btn-success quality-print','float'=>'left','lay-event'=>'quality-print'])
            ->addTopButton('add',['title' => '新增','href'=>url('mill/client/saleAdd'),'class'=>'btn btn-default','float'=>'left'])
            ->setRowList($data_list) // 设置表格数据
            ->setWidth('30%') // 设置表格宽度
            ->setColumnWidth([
                'id'  => 60,
            ])
            ->fetch(); // 渲染模板
    }
    //新增
    public function saleAdd()
    {
        $id = input('ids');
        if (strpos($id, ',') !== false)$this->error('暂不支持批量修改');
        $info = [];

        if ($this->request->isPost()) {
            $data = input();

            if(empty($data['staff'])) $this->error('请输入名称');

            if($id)$re = Db::name('mill_staff')->where(['id'=>$id])->update($data);
            else $re = Db::name('mill_staff')->insertGetId($data);

            //关闭子窗口，并刷新父窗口
            if ($re)$this->success('操作成功','','_parent_reload');
            $this->error('操作失败');
        }

        if($id)$info = Db::name('mill_sales')->where(['id'=>$id])->find();

        return ZBuilder::make('form')
            ->setPageTitle('新增') // 页面标题
            ->addFormItems([ // 批量添加表单项
                ['text:12||||must', 'staff', '人员名称'],
                //['static', 'static', ''],
                ['text:12', 'staff_mobile', '人员电话'],
                //['static', 'static', ''],
                ['radio:12', 'type', '人员类型','',ClientModel::$staff_type,1],
            ])
            ->setFormData($info)
            ->fetch();
    }
    //客户继承
    public function change($type = 1){

        $page_title_arr = [
            'title'     =>  '客户继承',
            'title2'     =>  '移交选项',
            'title3'     =>  '移交人',
            'title4'     =>  '接收人',
        ];
        if($type == 2){
            $page_title_arr = [
                'title'     =>  '客户归属',
                'title2'     =>  '归属选项',
                'title3'     =>  '客户原归属',
                'title4'     =>  '客户归属给',
            ];
        }

        if ($this->request->isPost()) {
            $data = input();

            if(empty($data['staff_id'])) $this->error('请选择'.$page_title_arr['title3']);
            if(empty($data['staff_id2'])) $this->error('请选择'.$page_title_arr['title4']);
            if(empty($data['ids'])) $this->error('请选择移交客户');

            $ids = implode($data['ids'],',');

            $re = Db::name('mill_client')->where([['id','in',$ids]])->update(['sales_id'=>$data['staff_id2']]);

            //关闭子窗口，并刷新父窗口
            if ($re)$this->success('操作成功','','_parent_reload');
            $this->error('操作失败');
        }

        $staff_list = ClientModel::getStaffList(1);

        $table_arr = ClientModel::fromSelect();
        $layui_head = $table_arr['layui_head'];
        $table_head = $table_arr['head'];
        $table_data = $table_arr['data'];

        $js = '<script type="text/javascript">
                
                //移交人点击事件
                $("body").on("change","select[name=\'staff_id\']",function(){
                    var staff_id = $(this).val();
                    
                    $.ajax({
                        url: \''.url("mill/client/changeList").'?type='.$type.'&staff_id=\'+staff_id,
                        type: \'GET\'
                    }).done(function(data) {
                    
                        form_table_tbody(data);
                        
                    })
                    
                });
            </script>';

        return ZBuilder::make('form')
            ->setPageTitle($page_title_arr['title']) // 页面标题
            ->addFormItems([ // 批量添加表单项
                ['ititle:12', 'ititle1', $page_title_arr['title2']],
                ['select', 'staff_id', $page_title_arr['title3'],'',$staff_list],
                ['select', 'staff_id2', $page_title_arr['title4'],'',$staff_list],
                ['complexTable2:12', 'client_list', '', $table_data, $table_head ,$layui_head,'','400'],
            ])
            ->setExtraJs($js)
            ->fetch();
    }
    //客户继承
    public function changeList($type = 1){

        $staff_id = input('staff_id');

        $where = [];
        if($type == 1)$where = ['c.sales_id'=>$staff_id];
        else if($type == 2)$where = ['c.sales_id'=>$staff_id];

        $list = [];
        if($staff_id){
            $list = Db::name('mill_client')
                ->alias('c')
                ->field('c.*,count(o.id) as order_sum,count(o.batch) as batch_sum,sum(a.row_area) as area_sum')
                ->leftJoin('mill_order o','o.client_id=c.id')
                ->leftJoin('mill_order_archives a','a.order_id=o.id')
                ->where($where)
                ->group('c.id')
                ->order('c.id desc')
                ->select();
        }

        $table_arr = ClientModel::fromSelect(['list'=>$list]);
        $table_head = $table_arr['head'];
        $table_data = $table_arr['data'];

        $tbody = '';
        if(!empty($table_data)){
            foreach ($table_data as $tdv){
                $tr = '<tr>';
                foreach ($tdv as $tdvv){
                    $tr .= '<td>'.$tdvv.'</td>';
                }
                $tr .='</tr>';

                $tbody .= $tr;
            }
        }

        exit($tbody);
    }
    //客户归属
    public function back(){
        return $this->change(2);
    }
    //客户归属
    public function backList(){
        return $this->changeList(2);
    }
    //冻结
    public function isLock($record = [])
    {
        return $this->setStatus('isLock');
    }
    //删除
    public function delete($record = [])
    {
        return $this->setStatus('delete');
    }
    //启用
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }
    //禁用
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }
    /**
     * 设置客户状态：删除、禁用、启用
     * @param string $type 类型：delete/enable/disable
     * @param array $record
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setStatus($type = '', $record = [])
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids = (array)$ids;

        foreach ($ids as $id) {

            switch ($type) {
                case 'isLock':
                    if (false === ClientModel::where('id', $id)->setField('is_lock', 0)) {
                        $this->error('冻结失败，工程ID：'.$id);
                    }
                    break;
                case 'enable':
                    if (false === ClientModel::where('id', $id)->setField('status', 1)) {
                        $this->error('启用失败，客户ID：'.$id);
                    }
                    break;
                case 'disable':
                    if (false === ClientModel::where('id', $id)->setField('status', 0)) {
                        $this->error('禁用失败，客户ID：'.$id);
                    }
                    break;
                case 'delete':

                    if (false === ClientModel::where('id', 'in', $id)->delete()) {
                        $this->error('删除失败，客户ID：'.$id);
                    }
                    break;
                default:
                    $this->error('非法操作');
            }

            action_log('role_'.$type, 'mill', $id, UID);
        }

        $this->success('操作成功');
    }

}
